import matplotlib.pyplot as plt
import numpy as np

#中文
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

def demonstrate_instantaneous_rate():
    """演示平均变化率如何趋近瞬时变化率"""
    # 定义函数：f(x) = x^2
    f = lambda x: x**2
    x0 = 2
    exact_derivative = 4  # f'(x) = 2x, f'(2)=4
    
    # 不同的Δx值
    delta_x_values = [2.0, 1.0, 0.5, 0.1, 0.01, 0.001]
    average_rates = []
    
    for dx in delta_x_values:
        average_rate = (f(x0 + dx) - f(x0)) / dx
        average_rates.append(average_rate)
        error = abs(average_rate - exact_derivative)
        print(f"Δx = {dx:.4f}, 平均变化率 = {average_rate:.4f}, 误差 = {error:.4f}")
    
    # 可视化
    plt.figure(figsize=(10, 6))
    plt.plot([1/dx for dx in delta_x_values], average_rates, 'bo-', label='平均变化率')
    plt.axhline(y=exact_derivative, color='r', linestyle='--', 
                label=f'瞬时变化率 f\'({x0}) = {exact_derivative}')
    
    plt.xlabel('1/Δx (精度增加方向)')
    plt.ylabel('变化率')
    plt.title('平均变化率趋近瞬时变化率 (f(x) = x²)')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.xscale('log')
    plt.show()

demonstrate_instantaneous_rate()